package com.tjetc.dao.impl;

import com.tjetc.dao.BookingDao;
import com.tjetc.pojo.entity.Booking;
import com.tjetc.pojo.vo.BookingVO;
import com.tjetc.utils.DruidUtils;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: itda
 * @Date: 2024/5/10 21:29
 * @Description: BookingDaoImpl
 */
public class BookingDaoImpl implements BookingDao {
    @Override
    public void insert(Booking booking) throws Exception {
        DruidUtils.r1.update(DruidUtils.getConnection(), "insert into booking (room_id, guest_id, payment_status, total_price, check_in_date, check_out_date) VALUES " +
                "(?,?,?,?,?,?)", booking.getRoomId(), booking.getGuestId(), booking.getPaymentStatus(), booking.getTotalPrice(), booking.getCheckInDate(), booking.getCheckOutDate());
    }

    @Override
    public void delete(Long id) throws Exception {
        DruidUtils.r1.update(DruidUtils.getConnection(), "delete from booking where id = ?", id);
    }

    @Override
    public void update(Booking booking) throws Exception {
        DruidUtils.r1.update(DruidUtils.getConnection(), "update booking set room_id = ?,guest_id = ?,payment_status = ?,total_price = ?,check_in_date = ?,check_out_date = ? where id = ?",
                booking.getRoomId(), booking.getGuestId(), booking.getPaymentStatus(), booking.getTotalPrice(), booking.getCheckInDate(), booking.getCheckOutDate(), booking.getId());
    }

    @Override
    public List<Booking> list() throws Exception {
        return DruidUtils.r2.query("select * from booking", new BeanListHandler<>(Booking.class, DruidUtils.rowProcessor));
    }

    @Override
    public List<BookingVO> getBookingByTime(LocalDateTime start, LocalDateTime end) throws Exception {
        return DruidUtils.r2.query("select b.room_id,g.id,u.username,u.email,u.phone,b.payment_status,b.total_price,b.check_in_date,b.check_out_date from user u ,booking b,guest g where b.guest_id = g.id and u.id = g.user_id and b.check_out_date between ? and ?", new BeanListHandler<>(BookingVO.class, DruidUtils.rowProcessor), start, end);
    }

    @Override
    public Booking getByRGId(Long roomId, Long guestId) throws Exception {
        return DruidUtils.r2.query("select * from booking where guest_id = ? and room_id = ?", new BeanHandler<>(Booking.class, DruidUtils.rowProcessor), guestId, roomId);
    }

    @Override
    public void setTotalMoney(Long id) throws Exception  {
        DruidUtils.r1.update(DruidUtils.getConnection(), "update booking set total_price = total_price * ? where id= ?", 0.9, id);
    }

    @Override
    public List<Booking> getByGuestId(Long guestId) throws Exception  {
        return DruidUtils.r1.query(DruidUtils.getConnection(),"select * from booking where guest_id = ?",new BeanListHandler<>(Booking.class,DruidUtils.rowProcessor),guestId);
    }
}
